//
//  HttpClient.swift
//  home
//
//  Created by Yun Zeng on 2019/9/23.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import Foundation

fileprivate let cloudHTTPURL = URL(string: "http://adai.design:6666/member")!

class HttpClient {
    
    struct MsgInfo: Codable {
        var membership: String
        var session: String?
        var dev_t: String?
        var home: String?
        var state: String?
        var message: CloudMessage
    }
    
    static func post(membership: Membership, home: String?, message: CloudMessage, completionHandler: @escaping (CloudMessage?) -> Void) -> Bool {
        if membership.uuid == nil || membership.token == "" {
            return false
        }
        
        let info = MsgInfo(membership: membership.uuid!, session: membership.token!, dev_t: DevType, home: home, message: message)
        
        var request = URLRequest(url: cloudHTTPURL)
        request.httpMethod = "POST"
        var headers = request.allHTTPHeaderFields ?? [:]
        headers["Content-Type"] = "application/json"
        request.allHTTPHeaderFields = headers
        request.httpBody = try! JSONEncoder().encode(info)
        
        let session = URLSession(configuration: URLSessionConfiguration.default)
        let task = session.dataTask(with: request) { (responseData, response, responseError) in
            guard responseError == nil else {
                Logger.Error(responseError.debugDescription)
                return
            }
            if let data = responseData  {
//                Logger.Info("response: \(utf8Representation)", utf8Representation)
                if let rsp = try? JSONDecoder().decode(HttpClient.MsgInfo.self
                    , from: data) {
                    if rsp.state != nil && rsp.state == "ok" {
                        completionHandler(rsp.message)
                    }
                } else {
                    completionHandler(nil)
                }

            } else {
                Logger.Error("no readable data received in response")
            }
        }
        task.resume()
        return false
    }
    
    
    
}
